<template>
	<div>
		<el-dialog :title="detail.theme || '活动主题'" :visible.sync="dialogVisible" :close-on-click-modal="false" width="750px" @close="close">
			<div v-loading="loading" class="content">
				<el-form v-if="detail && row" ref="form" label-width="140px" size="small">
					<el-form-item label="活动封面："><img v-if="detail.image" :src="fileBaseUrl + detail.image" class="poster-img" alt /></el-form-item>
					<el-form-item label="活动主题：">{{ detail.theme }}</el-form-item>
					<el-form-item label="活动类型：">
						<div>{{ detail.onlyMemberDay ? '会员日' : '' }}{{ $store.state.setting.marketingActivityTypeKeyOptions[detail.activityType] || '-' }}</div>
					</el-form-item>
					<el-form-item label="活动状态：">
						<el-tag v-if="detail.status === 1" size="mini" type="success">启用中</el-tag>
						<el-tag v-if="detail.status === 2" size="mini" type="danger">已暂停</el-tag>
						<el-tag v-if="detail.status === 3" size="mini" type="info">已终止</el-tag>
					</el-form-item>
					<el-form-item label="活动时间：">{{ detail.startTime + ' ~ ' + detail.endTime }}</el-form-item>
					<el-form-item label="参与时间：">
						<div v-if="detail.useRule === 1">有效期内所有时间都可以参与活动</div>
						<div v-else-if="detail.useRule === 2 || detail.useRule === 3">
							<div v-if="detail.useRule === 2">{{ detail.ruleDataWeek }}</div>
							<div v-else-if="detail.useRule === 3">
								<div v-for="(item, index) in detail.ruleDataDate" :key="'date' + index">{{ item.date[0] + ' ~ ' + item.date[1] }}</div>
							</div>
							<div v-for="(item, index) in detail.ruleDataTime" :key="'time' + index">{{ item.time[0] + ' ~ ' + item.time[1] }}</div>
						</div>
					</el-form-item>
					<el-form-item label="参与对象：">
						<div v-if="detail.participant === 1">所有人</div>
						<div v-else-if="detail.participant === 2">所有会员</div>
						<div v-else-if="detail.participant === 3 || detail.participant === 6">{{ detail.activityLimit }}</div>
						<div v-else-if="detail.participant === 4">指定手机用户</div>
						<div v-else-if="detail.participant === 5">指定银行卡用户</div>
					</el-form-item>
					<el-form-item v-if="detail.activityType === 4 && (detail.participant === 4 || detail.participant === 5) && detail.matchPrecision" label="手机号匹配精度：">
						<div>{{ detail.matchPrecision.split(',')[0] || 99 }} 位</div>
					</el-form-item>
					<el-form-item v-if="detail.activityType === 4 && detail.participant === 5 && detail.matchPrecision" label="银行卡匹配精度：">
						<div>{{ detail.matchPrecision.split(',')[1] || 99 }} 位</div>
					</el-form-item>
					<div v-if="[1, 2, 3, 4].includes(detail.activityType)">
						<el-form-item v-if="[1, 3].includes(detail.activityType)" label="规则类型：">
							<div v-if="detail.calculateTypeExtra === 1">
								<span v-if="detail.activityType === 1">按阶梯赠礼</span>
								<span v-if="detail.activityType === 3">按阶梯返微信红包</span>
							</div>
							<div v-if="detail.calculateTypeExtra === 2">
								<span v-if="detail.activityType === 1">消费每满赠礼</span>
								<span v-if="detail.activityType === 3">支付每满返微信红包</span>
							</div>
						</el-form-item>
						<el-form-item v-if="detail.activityType === 1" label="规则配置：">
							<el-table :data="detail.award" border stripe size="small" empty-text="暂未配置规则" style="width: 100%">
								<el-table-column prop="amount" label="消费金额/元" width="150">
									<!--                <template slot-scope="scope">{{ scope.row.amount }}</template>-->
								</el-table-column>
								<el-table-column label="赠礼">
									<template slot-scope="scope">
										<div v-if="scope.row.awardTypeExtra.includes('bonusBalance')">
											<span class="award-type-icon award-type-icon-balance">金</span>
											&nbsp;&nbsp; 按照固定金额赠送{{ scope.row.balance }}元
										</div>
										<div v-if="scope.row.awardTypeExtra.includes('bonusPoint')">
											<span class="award-type-icon award-type-icon-point">积</span>
											&nbsp;&nbsp; 赠送积分{{ scope.row.points }}个
										</div>
										<div v-if="scope.row.awardTypeExtra.includes('bonusCardCoupon')">
											<div v-for="(couponItem, couponIndex) in scope.row.couponData" :key="couponIndex">
												<span v-if="['times', 'gift'].includes(couponItem.couponType)" class="award-type-icon award-type-icon-coupon">卡</span>
												<span v-else class="award-type-icon award-type-icon-coupon">券</span>
												&nbsp;&nbsp; 赠送卡券{{ '【' + couponItem.name + '】' + couponItem.num }}张
												<!--                      &nbsp;&nbsp;-->
												<!--                      <el-button-->
												<!--                        type="text"-->
												<!--                        size="small"-->
												<!--                        @click="openCouponDetail(couponItem.couponId)"-->
												<!--                      >详情-->
												<!--                      </el-button>-->
											</div>
										</div>
									</template>
								</el-table-column>
							</el-table>
						</el-form-item>
						<el-form-item v-if="detail.activityType === 3" label="规则配置：">
							<el-table :data="detail.award" border stripe size="small" empty-text="暂未配置规则" style="width: 100%">
								<el-table-column prop="amount" label="消费金额/元" width="150" />
								<el-table-column prop="balance" label="红包金额/元" />
							</el-table>
						</el-form-item>
						<el-form-item v-if="detail.activityType === 4" label="规则配置：">
							<el-table :data="(detail.award.length && detail.award[0].couponData) || []" border stripe size="small" empty-text="暂未配置规则" style="width: 100%">
								<el-table-column prop="couponId" label="批次号" />
								<el-table-column prop="name" label="卡券名称" />
								<el-table-column prop="couponType" label="卡券类型">
									<template slot-scope="scope">
										{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
									</template>
								</el-table-column>
								<el-table-column prop="num" label="数量" />
							</el-table>
						</el-form-item>
					</div>
					<div v-if="[5, 6, 7, 8].includes(detail.activityType)">
						<el-form-item label="营销规则：">
							<div v-for="item in detail.singleRules" :key="item.threshold">
								<div v-if="detail.activityType === 5">活动商品国际条码任意一个或多个消费满{{ item.threshold }}元立减{{ item.amount }}元</div>
								<div v-if="detail.activityType === 6">每一个商品国际条码买{{ item.threshold }}件，其中{{ item.amount }}件免单</div>
								<div v-if="detail.activityType === 7">
									<span v-if="item.everyOne">购买同国际条码商品，满</span>
									<span v-else>购买同国际条码商品，仅第</span>
									<span>{{ item.threshold }}</span>
									<span v-if="item.everyOne">件，或者更多时每件商品均享受</span>
									<span v-else>件享受</span>
									<span>{{ item.amount }}</span>
									<span>折</span>
								</div>
								<div v-if="detail.activityType === 8">
									<span v-if="item.everyOne">购买同国际条码商品，满</span>
									<span v-else>购买同国际条码商品，仅第</span>
									<span>{{ item.threshold }}</span>
									<span v-if="item.everyOne">件或者更多时每件商品均享受立减到</span>
									<span v-else>件享受立减到</span>
									<span>{{ item.amount }}</span>
									<span>元</span>
								</div>
							</div>
						</el-form-item>
						<el-form-item label="活动商品国际条码：">{{ detail.singleGoods }}</el-form-item>
						<el-form-item label="整单优惠同享：">
							<span v-if="detail.discountSharing">可同享</span>
							<span v-else>不可同享</span>
						</el-form-item>
					</div>

					<el-form-item label="活动限制：">
						<div v-if="detail.frequencyDay == -1 && detail.frequencyWeek == -1 && detail.frequencyMonth == -1 && detail.frequencyAll == -1">无限制</div>
						<div v-if="detail.frequencyDay != -1">一个用户一天可参与活动 {{ detail.frequencyDay }} 次</div>
						<div v-if="detail.frequencyWeek != -1">一个用户一周可参与活动 {{ detail.frequencyWeek }} 次</div>
						<div v-if="detail.frequencyMonth != -1">一个用户一月可参与活动 {{ detail.frequencyMonth }} 次</div>
						<div v-if="detail.frequencyAll != -1">一个用户累计可参与活动 {{ detail.frequencyAll }} 次</div>
					</el-form-item>
					<el-form-item label="活动预算：">
						<div v-if="detail.budget == -1">活动总预算无限制</div>
						<div v-else>活动总预算 {{ detail.budget }} 次</div>
						<div v-if="detail.perdayBudget == -1">单天活动预算无限制</div>
						<div v-else>单天活动预算 {{ detail.perdayBudget }} 次</div>
					</el-form-item>
					<el-form-item label="参与门店：">
						<div v-if="detail.shop.length === 0">全部门店</div>
						<div v-else>{{ detail.shop.length }}家门店</div>
						<div v-if="detail.shopListNameStr">{{ detail.shopListNameStr }}</div>
					</el-form-item>
					<el-form-item label="交易类型：">
						<div v-if="detail.bizType.length === 0">全部交易类型</div>
						<template v-for="(item, index) in detail.bizType">
							<span :key="item">
								{{ bizCodeKeyOptions[item] || item }}
								<span v-if="index != detail.bizType.length - 1">、</span>
							</span>
						</template>
					</el-form-item>
					<el-form-item label="支付方式：">
						<div v-if="detail.payType.length === 0">全部支付方式</div>
						<template v-for="(item, index) in detail.payType">
							<span :key="item">
								{{ paymentKeyOptions[item] || item }}
								<span v-if="index != detail.payType.length - 1">、</span>
							</span>
						</template>
					</el-form-item>
					<el-form-item v-if="detail.limitPay" label="付款方式：">
						<div v-if="detail.limitPay === 1">全部付款方式</div>
						<div v-if="detail.limitPay === 2 || detail.limitPay === 3">
							<span v-if="detail.limitPay === 2">指定银行</span>
							<span v-if="detail.limitPay === 3">排除银行</span>
							：
							<span v-for="(code, codeIndex) in detail.bankCode" :key="code">{{ codeIndex ? '、' : '' }}{{ wxPayCardNameOptions[code] || code }}</span>
						</div>
					</el-form-item>
				</el-form>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getActivityDetailById } from '@/api/marketing';
import { getShopListByIds } from '@/api/shop';
import { wxPayCardNameOptions } from '@/assets/json/wxpay-bank';

export default {
	components: {},
	data() {
		return {
			// 配置
			wxPayCardNameOptions: wxPayCardNameOptions,
			resolve: null,
			reject: null,
			// 状态
			loading: false,
			dialogVisible: false,
			// 数据
			id: '',
			row: '',
			detail: ''
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl', 'paymentKeyOptions', 'bizCodeKeyOptions'])
	},
	methods: {
		open(row) {
			this.row = row;
			this.id = row.id;
			this.getDetail();
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},

		show() {
			this.dialogVisible = true;
		},

		close() {
			this.prototype = null;
			this.availablePeriods = null;
			this.timeType = null;
		},

		hide() {
			this.resolve = null;
			this.reject = null;
			this.dialogVisible = false;
		},

		/**
		 * 获取数据
		 */
		getDetail() {
			this.loading = true;
			getActivityDetailById({ id: this.id })
				.then(res => {
					// 重置回表单数据
					let data = {};
					data = res.data.activity;
					data.award = res.data.awards;
					data.singleGoods = res.data.goodsCodes || [];
					data.singleRules = res.data.singleItemRules || [];
					data.activityLimit = res.data.activityLimit;
					this.formatData(data);
				})
				.catch(err => {
					this.loading = false;
				})
				.finally(() => {});
		},

		// 格式化数据
		async formatData(data) {
			// 时间
			if (data.useRule !== 1) {
				const ruleDataDateArr = [];
				const ruleDataTimeArr = [];
				data.ruleDataTime = data.ruleDataTime.split(',');
				data.ruleDataTime.forEach(v => {
					ruleDataTimeArr.push({
						time: [this.$options.filters.minsToHourMins(v.split('-')[0]), this.$options.filters.minsToHourMins(v.split('-')[1])]
					});
				});
				data.ruleDataTime = ruleDataTimeArr;
				switch (data.useRule) {
					case 2:
						data.ruleDataWeek = this.$options.filters.weekNum2WeekStr(data.ruleDataWeek);
						data.ruleDataDate = [{ date: '' }];
						break;
					case 3:
						data.ruleDataTime = [{ time: ['00:00', '23:59'] }];
						data.ruleDataDate = data.ruleDataDate.split(',');
						data.ruleDataDate.forEach(v => {
							ruleDataDateArr.push({
								date: [v.split(':')[0], v.split(':')[1]]
							});
						});
						data.ruleDataDate = ruleDataDateArr;
						break;
				}
			}

			// 奖励规则
			switch (data.activityType) {
				case 1:
				case 2:
				case 3:
				case 4:
					data.calculateTypeExtra = data.award[0].calculateType;
					data.award.forEach(v => {
						v.awardTypeExtra = [];
						// 消费金额
						v.amount = v.amount / 100;
						// 余额
						if (v.bonusBalance) {
							v.awardTypeExtra.push('bonusBalance');
							v.balance = v.balance / 100;
						}
						//  积分
						if (v.bonusPoint) {
							v.awardTypeExtra.push('bonusPoint');
						}
						// 券
						if (v.bonusCoupon) {
							// v.awardTypeExtra.push('bonusCoupon')
							// v.couponData = JSON.parse(v.couponData)
							v.couponData = JSON.parse(v.couponData);

							let version = 2; // 判断是v1 还是v2
							v.couponData.some((v, i) => {
								if (i === 0) {
									version = ['CASH', 'DISCOUNT', 'GENERAL'].includes(v.couponType) ? 1 : 2;
									return true;
								}
							});
							v.awardTypeExtra.push(version === 2 ? 'bonusCardCoupon' : 'bonusCoupon');
						} else {
							v.couponData = [];
						}
					});

					break;
				case 5:
				case 6:
				case 7:
				case 8:
					data.singleRules.forEach(v => {
						if (data.activityType === 5) {
							v.threshold = this.$math.div(v.threshold, 100, 2);
							v.amount = this.$math.div(v.amount, 100, 2);
						}
						if (data.activityType === 7) {
							v.amount = this.$math.div(v.amount, 10, 1);
						}
						if (data.activityType === 8) {
							v.amount = this.$math.div(v.amount, 100, 2);
						}
					});
					data.singleGoods = data.singleGoods.join('、');
					break;
			}

			// 门店
			data.shop = data.shop ? data.shop.split(',') : [];
			// 交易类型
			data.bizType = data.bizType ? data.bizType.split(',') : [];
			// 支付方式
			data.payType = data.payType ? data.payType.split(',') : [];
			// 付款方式
			data.bankCode = data.bankCode ? data.bankCode.split(',') : [];

			this.detail = data;

			await this.getShopList();
			this.loading = false;
			this.show();
		},

		// 获取可用门店列表
		getShopList() {
			return new Promise((resolve, reject) => {
				if (this.detail.shop && this.detail.shop.length) {
					getShopListByIds({ idList: this.detail.shop })
						.then(res => {
							if (res.data && res.data.length > 0) {
								const nameArr = [];
								res.data.forEach(v => {
									nameArr.push(v.name);
								});
								const nameStr = nameArr.join('、');
								this.detail.shopListNameStr = nameStr;
							}
						})
						.catch(() => {})
						.finally(() => {
							resolve();
						});
				} else {
					resolve();
				}
			});
		},

		/**
		 * 按钮组
		 */
		// 打开券详情
		openCouponDetail(id) {
			this.$refs.couponDetail.open(id);
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
	min-height: 400px;

	.el-form-item {
		margin-bottom: 0;
	}

	.poster-img {
		width: 200px;
		height: 117px;
	}

	/* 奖励类型icon文字*/
	.award-type-icon {
		display: inline-block;
		width: 18px;
		height: 18px;
		line-height: 18px;
		text-align: center;
		color: #fff;
	}

	.award-type-icon-balance {
		background-color: #f59a23;
	}

	.award-type-icon-point {
		background-color: #10aeff;
	}

	.award-type-icon-coupon {
		background-color: #fa5151;
	}
}
</style>
